package com.splant.android.smart.UILevel.Community.fragments;


import android.app.Fragment;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.DeviceListBean;
import com.splant.android.smart.SystemDefinedLevel.DeciveManager.DeviveMessages;
import com.splant.android.smart.SystemDefinedLevel.DeciveManager.ScreenInfo;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.widget.MapViewLayout;
import org.apache.http.Header;
import org.json.JSONObject;

public class Garden_Map_Fragment extends Fragment {


    private String areaId="";
    public void selectArea() {
        if (tv_areaName!=null)
        {
            String curAreaName=tv_areaName.getText().toString();
            if (Global.selectedArea!=null&&curAreaName.equals("选择区域")==false&&Global.selectedArea.getAreaId().equals(areaId)==false)
            {
                updateDatas();
            }
        }
    }
    private View mView;
    private ImageView img_map;
    private MapViewLayout mapViewLayout;
    private ScreenInfo screenInfo;
    private ImageButton imgBtn_update;
    private ImageButton imgBtn_zoomIn;
    private ImageButton imgBtn_zoomOut;
    private CheckBox chk_shDevice;
    private TextView tv_areaName;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_map_fragment, null);
            img_map = (ImageView) mView.findViewById(R.id.img_map);
            imgBtn_update = (ImageButton) getActivity().findViewById(R.id.imgBtn_update);
            imgBtn_zoomIn = (ImageButton) getActivity().findViewById(R.id.imgBtn_zoomIn);
            imgBtn_zoomOut = (ImageButton) getActivity().findViewById(R.id.imgBtn_zoomOut);
            tv_areaName = (TextView) getActivity().findViewById(R.id.tv_areaName);
            chk_shDevice= (CheckBox) getActivity().findViewById(R.id.chk_shDevice);

            screenInfo = DeviveMessages.getScreenInfo(getActivity(), getActivity().getWindowManager());
            mapViewLayout = (MapViewLayout) mView.findViewById(R.id.mvl_map);

            init();

            imgBtn_update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateDatas();
                }
            });
            imgBtn_zoomIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mapViewLayout.zoomMap(true);

                }
            });
            imgBtn_zoomOut.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mapViewLayout.zoomMap(false);
                }
            });
            chk_shDevice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mapViewLayout.showHideDeviceName(isChecked);
                }
            });

            showBtn();
        }
        return mView;
    }

    public void showBtn() {

        if (chk_shDevice!=null)
            chk_shDevice.setVisibility(View.VISIBLE);

        if (imgBtn_update != null)
            imgBtn_update.setVisibility(View.VISIBLE);

        if (imgBtn_zoomIn != null)
            imgBtn_zoomIn.setVisibility(View.VISIBLE);

        if (imgBtn_zoomOut != null)
            imgBtn_zoomOut.setVisibility(View.VISIBLE);

    }

    public void hideBtn() {

        if (chk_shDevice!=null)
            chk_shDevice.setVisibility(View.GONE);

        if (imgBtn_update != null)
            imgBtn_update.setVisibility(View.GONE);

        if (imgBtn_zoomIn != null)
            imgBtn_zoomIn.setVisibility(View.GONE);

        if (imgBtn_zoomOut != null)
            imgBtn_zoomOut.setVisibility(View.GONE);

    }

    private sPlantAsyncHttpClient sPlantClient;

    private void init() {

        sPlantClient = sPlantAsyncHttpClient.getInstance();

        loadingDialog = LoadingDialog.createDialog(getActivity());

        updateDatas();
    }

    private LoadingDialog loadingDialog;

    private void updateDatas() {

        if (loadingDialog.isShowing() == false)
            loadingDialog.show();

        if (Global.selectedArea==null||Global.selectedArea.getAreaId().equals(""))
            getAreaList();
        else {
            areaId=Global.selectedArea.getAreaId();
            loadMap(Global.selectedArea.getAreaMapUrl());
        }

    }

    private void getAreaList() {

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try {
                            if (response.getInt("succeed") == 1) {

                                Gson gson = new Gson();
                                AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);

                                if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0)
                                {
                                    if (Global.selectedArea==null||Global.selectedArea.getAreaId().equals(""))
                                          Global.selectedArea=areaListBean.getAreaList().get(0);

                                    areaId=Global.selectedArea.getAreaId();

                                    tv_areaName.setText(Global.selectedArea.getAreaName());

                                    loadMap(Global.selectedArea.getAreaMapUrl());

                                } else {
                                    areaId="";
                                    loadMap(Global.user.getMapUrl());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                        Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();

                    }
                });

    }

    public void openedAreaDevicesSuccess() {
        mapViewLayout.allWatersOpenedSwitchs();
    }

    public void closedAreaDeviceSuccess()
    {
        mapViewLayout.allWaterClosedSwitchs();
    }

    public void openedAreaDevicesFailure(String waterIds, int waterLength) {

        mapViewLayout.watersOpenedFailure(waterIds,waterLength);

    }

    private void loadMap(String mapUrl) {

        Glide.with(getActivity()).load(mapUrl).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                int w = resource.getWidth();
                int h = resource.getHeight();

                mapViewLayout.initMap(getActivity(), img_map, w, h, screenInfo.getScreenWidth(), System_Dimen_Util.dip2px(getActivity(), 400));

                img_map.setImageBitmap(resource);

                loadDevices();
            }
        });

    }

    private void loadDevices() {

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        String areaId = "";
        if (Global.selectedArea != null)
            areaId = Global.selectedArea.getAreaId();

        params.put("areaId", areaId);

        sPlantClient.get(sPlantAsyncHttpClient.GETAREADEVICES, params, new sPlantJsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {

                    loadingDialog.dismiss();
                    if (response.getInt("succeed") == 1) {

                        Gson gson = new Gson();
                        DeviceListBean deviceListBean = gson.fromJson(response.toString(), DeviceListBean.class);

                        mapViewLayout.removeAllDeviceViews();

                        if (deviceListBean.getWaterList() != null) {
                            mapViewLayout.addWaterList(deviceListBean.getWaterList());
                        }
                        if (deviceListBean.getDetectorList() != null) {
                            mapViewLayout.addDetectorList(deviceListBean.getDetectorList());
                        }

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                loadingDialog.dismiss();
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();

            }
        });
    }

}
